package subsystems

import (
	"bufio"
	"fmt"
	"os"
	"path"
	"strings"
)

// FindCGroupMountPoint 查找CGroup挂载点
func FindCGroupMountPoint(subSystem string) string {
	filePtr, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		return ""
	}
	defer filePtr.Close()

	scannerPtr := bufio.NewScanner(filePtr)
	for scannerPtr.Scan() {
		text := scannerPtr.Text()
		fieldSlc := strings.Split(text, " ")
		// 最后一个元素用,切割
		for _, opt := range strings.Split(fieldSlc[len(fieldSlc)-1], ",") {
			if opt == subSystem {
				return fieldSlc[4]
			}
		}
	}
	if err := scannerPtr.Err(); err != nil {
		return ""
	}
	return ""
}

// GetCGroupPath 获取jodocker-cgroup路径
func GetCGroupPath(subSystem string, cGroupPath string, autoCreate bool) (string, error) {
	cGroupRootPath := FindCGroupMountPoint(subSystem)
	if _, err := os.Stat(path.Join(cGroupRootPath, cGroupPath)); err == nil || (autoCreate && os.IsNotExist(err)) {
		if os.IsNotExist(err) {
			// 不存在,创建
			if err := os.Mkdir(path.Join(cGroupRootPath, cGroupPath), 0755); err == nil {

			} else {
				return "", fmt.Errorf("error create cgroup fail %v", err)
			}
		}
		return path.Join(cGroupRootPath, cGroupPath), nil
	} else {
		return "", fmt.Errorf("CGroup path error %v", err)
	}
}
